package com.chj.leetcode.tijie150to200;

public class Code160_IntersectionOfTwoLinkedLists {

	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}

	public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		int aLen = length(headA);
		int bLen = length(headB);
		while (aLen != bLen) {
			if (aLen > bLen) {
				headA = headA.next;
				aLen--;
			} else {
				headB = headB.next;
				bLen--;
			}
		}

		while (headA != headB) {
			headA = headA.next;
			headB = headB.next;
		}

		return headA;
	}

	// 统计链表的长度
	private int length(ListNode node) {
		int n = 0;
		while (node != null) {
			node = node.next;
			n++;
		}

		return n;
	}
}
